<template>
  <div class="container">
    <div v-show="!scanNo">
      <page-header
        :title="
          problemType == 2 ? $t('Report_reportFaulty') : $t('home_reportIssue')
        "
      ></page-header>
      <div class="problem_div">
        <div class="problem_title" v-if="problemType == 2">
          {{ $t('Report_selectFault') }}
        </div>
        <div class="problem_title problem_title2" v-else>
          {{ $t('home_unfotunatelyText') }}
        </div>
        <div class="problem_select" v-if="problemType == 2">
          <div
            class="problem_select_content"
            :class="{
              problem_select_active: params.damageType.includes(item.value)
            }"
            v-for="item in problemOptions"
            :key="item.value"
            @click="changeValue(item.value)"
          >
            <div class="problem_select_title">{{ item.label }}</div>
            <img
              style="width: 14px; height: 14px;"
              :src="
                params.damageType.includes(item.value)
                  ? require('@/assets/img/problem/ic_selected.svg')
                  : require('@/assets/img/problem/ic_unselected@2x.png')
              "
            />
          </div>
        </div>
        <div class="problem_input">
          <el-input
            v-model="params.cabinetNo"
            clearable
            @input="onInput"
            :maxlength="20"
            :placeholder="$t('toast_enterStationID')"
          />
          <img
            style="width: 44px; height: 44px;"
            src="@/assets/img/problem/ic_camera@2x.png"
            @click="scanId"
          />
        </div>
        <div class="problem_input_textarea">
          <el-input
            type="textarea"
            v-model="params.description"
            :maxlength="300"
            :placeholder="$t('home_describeIssueText')"
          ></el-input>
          <div class="textarea_maxlength" style="margin:3px 0;">
            {{ params.description.length }} / 300
          </div>
          <div class="textarea_img">
            <div class="textarea_img_div">
              <van-uploader
                :after-read="afterRead"
                :before-read="beforeRead"
                accept="image/*"
                v-model="fileList"
                :max-count="3"
                @delete="deleteImg"
              >
                <img
                  class="textarea_image"
                  style="border:none;margin-right: 0px;"
                  src="@/assets/img/problem/Add@2x.png"
                />
              </van-uploader>
            </div>
            <div class="textarea_maxlength">{{ fileList.length }} / 3</div>
          </div>
        </div>
      </div>
      <bottom-button :title="$t('home_submit')" @click="submit"></bottom-button>
    </div>
    <div style="width: 100%;" v-if="scanNo">
      <img
        src="@/assets/img/common/ic_back@2x.png"
        alt=""
        class="backImg"
        @click="scanNo = false"
      />
      <qrcode-stream
        @decode="onDecode"
        @init="scanNo ? onInit() : ''"
        ref="qrcodeStream"
      >
        <div class="scanIcon">
          <div class="input_sno" id="snoId"></div>
          <div :style="codeStyle">
            <div class="qr-scanner">
              <div class="box">
                <div class="line"></div>
                <div class="angle"></div>
              </div>
            </div>
          </div>
        </div>
      </qrcode-stream>
    </div>
  </div>
</template>
<script>
import $api from '@/assets/js/api/home'
import share from '@/mixins/share'
export default {
  mixins: [share],
  data () {
    return {
      problemOptions: [],
      params: {
        cabinetNo: '', //	机柜编号
        damageType: [], //	报损类型：1-线头 2-头坏 3-充电宝坏 4-指示灯损坏 0-其他(多选，逗号隔开)
        description: '', //	描述信息
        images: '', //	图片 ','号分割
        orderNo: '', //	订单号
        orderType: '' // 1、充电宝不弹出 2、充电宝归还不结束
      },
      problemType: 1, // 1、上报问题； 2、充电宝报损
      uploadImgs: [], // 传给后台的路径
      fileList: [], // 预览的路径
      scanNo: false,
      snoWidth: '',
      windowWidth: document.body.clientWidth
    }
  },
  watch: {
    // 监听页面宽度
    windowWidth (val) {
      // console.log('实时屏幕宽度：', val, this.windowHeight)
      if (this.scanNo) {
        this.getWidth()
      }
    }
  },
  computed: {
    codeStyle () {
      return {
        '--snoWidth': this.snoWidth
      }
    }
  },
  created () {
    this.getLang()
    let params = JSON.parse(this.$route.query.params);
    this.params.orderNo = params.orderNo;
    this.params.penaltyAmount = params.penaltyAmount;
    this.params.orderType = params.orderType || "";
    this.problemType = params.problemType;
    this.problemOptions = [
      {
        value: '1',
        label: this.$t('home_cableFaulty')
      },
      {
        value: '2',
        label: this.$t('home_brokenTip')
      },
      {
        value: '3',
        label: this.$t('home_canNotCharge')
      },
      {
        value: '4',
        label: this.$t('home_indicatorError')
      },
      {
        value: '5',
        label: this.$t('home_other')
      }
    ]
  },
  mounted () {
    // this.getWidth()
    window.onresize = () => {
      return (() => {
        this.windowWidth = document.documentElement.clientWidth // 宽
      })()
    }
  },
  methods: {
    //获取宽度
    getWidth () {
      this.$nextTick(() => {
        let snoId = document.getElementById('snoId')
        this.snoWidth = snoId.clientWidth + 'px'
        // console.log(this.snoWidth)
      })
    },

    // 解码
    onDecode (result) {
      const urlSno = result.includes('https://links.joltzly.com/')
        ? result.replace('https://links.joltzly.com/', '')
        : ''
      this.params.cabinetNo = urlSno || this.global.getSearchString('sno', result) || this.global.getSearchString('id', result) || ''
      if (!this.params.cabinetNo) {
        this.global.toast(this.$t('toast_validQRCode'))
        this.$refs.qrcodeStream.reset()
        return
      }
      this.scanNo = false
    },

    async onInit (promise) {
      try {
        await promise
      } catch (error) {
        let msg = ''
        if (error.name === 'NotAllowedError') {
          msg = this.$t('Error_camera_access')
        } else if (error.name === 'NotFoundError') {
          msg = this.$t('Error_No_camera')
        } else if (error.name === 'NotSupportedError') {
          msg = this.$t('Error_secure_context')
        } else if (error.name === 'NotReadableError') {
          msg = this.$t('Error_camera_inuse')
        } else if (error.name === 'OverconstrainedError') {
          msg = this.$t('Error_camera_improper')
        } else if (error.name === 'StreamApiNotSupportedError') {
          msg = this.$t('Error_streamapi')
        } else if (error.name === 'InsecureContextError') {
          msg = this.$t('Error_camera_permission')
        } else {
          msg = `ERROR: ${$t('Error_camera')} (${error.name})`
        }
        this.global.toast(msg)
      }
    },

    //限制输入
    onInput (e) {
      const inputNum = e
      this.params.cabinetNo = inputNum.replace(/[^a-zA-Z0-9]/g, '')
    },

    //选择报损类型
    changeValue (val) {
      const index = this.params.damageType.indexOf(val)
      if (index > -1) {
        this.params.damageType.splice(index, 1)
      } else {
        this.params.damageType.push(val)
      }
    },

    //扫码获取机柜ID
    scanId () {
      this.scanNo = true
      this.getWidth()
    },

    //图片上传前限制
    beforeRead (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      if (!isJPG) {
        this.global.toast(this.$t('Upload_image_type'))
        return false
      }
      return true
    },

    // 将文件上传至服务器
    afterRead (file) {
      let params = new FormData()
      params.append('files', file.file)
      params.append('type', 1)
      $api.uploadImg(params).then(res => {
        if (res.code == 0) {
          this.global.toast(res.message)
          this.uploadImgs.push(res.data.value)
        } else {
          this.global.toast(res.message)
        }
      })
    },

    //删除图片
    deleteImg (file, detail) {
      let params = { file: this.uploadImgs[detail.index] }
      this.uploadImgs.splice(detail.index, 1)
      $api.deldImg(params).then(res => {
        if (res.code == 0) {
          this.global.toast(res.message)
        }
      })
    },

    //充电宝报损
    postOrdersDamages (item) {
      $api.postOrdersDamage(item).then(res => {
        if (res.code == 0) {
          this.global.toast(res.message)
          let params = {
            type: 3
          }
          this.$router.push({
            path: '/problem/result',
            query: {
              params: JSON.stringify(params),
              feebackOrigin: 1 //1 意见反馈
            }
          })
        } else {
          this.global.toast(res.message)
        }
      })
    },

    //上报-订单问题
    postOrdersProblems (item) {
      $api.postOrdersProblem(item).then(res => {
        if (res.code == 0) {
          this.global.toast(res.message)
          let params = {
            type: 3,
            penaltyAmount: this.params.penaltyAmount
          }
          this.$router.push({
            path: '/problem/result',
            query: {
              params: JSON.stringify(params)
            }
          })
        } else {
          this.global.toast(res.message)
        }
      })
    },

    //提交反馈
    submit () {
      if (this.params.damageType.length == 0 && this.problemType == 2) {
        this.global.toast(this.$t('Report_selectFault'))
        return
      }

      if (!this.params.cabinetNo) {
        this.global.toast(this.$t('toast_enterStationID'))
        return
      }
      if (!this.params.description) {
        this.global.toast(this.$t('home_describeIssueText'))
        return
      }
      if (this.uploadImgs.length == 0) {
        this.global.toast(this.$t('Report_errorImg'))
        return
      }
      this.params.images = this.uploadImgs.toString()
      let params = JSON.parse(JSON.stringify(this.params))
      params.damageType = params.damageType.toString()
      if (this.problemType == 2) {
        delete params.orderType
        this.postOrdersDamages(params)
      } else {
        delete params.damageType
        this.postOrdersProblems(params)
      }
    }
  }
}
</script>

<style lang="scss">
.container {
  background: #f5f5f7;
  .problem_div {
    width: calc(100% - 40px);
    padding: 26px 20px 108px;
    .problem_title {
      font-size: 17px;
      font-weight: 600;
      text-align: left;
      color: #39404d;
      line-height: 20px;
    }
    .problem_title2 {
      line-height: 24px !important;
    }
    .problem_select {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      .problem_select_content {
        width: calc(50% - 5px);
        background: #f5f5f7;
        border: 1px solid #d2d8e2;
        border-radius: 10px;
        padding: 0 14px;
        min-height: 48px;
        margin: 10px 10px 0 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        &:nth-of-type(2n) {
          margin-right: 0;
        }
        .problem_select_title {
          font-size: 14px;
          font-weight: 500;
          text-align: left;
          color: #39404d;
          line-height: 16px;
          margin-right: 12px;
        }
      }
      .problem_select_active {
        border: 2px solid #E7FF55;
        padding: 0 13px !important;
        background: #ffffff;
      }
    }
    .problem_input {
      height: 48px;
      background: #ececee;
      border-radius: 7px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 14px 0 0;
      margin: 20px 0 10px 0;
      .el-input__inner {
        height: 48px !important;
        border: none !important;
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        color: #39404d;
        line-height: 16px;
        background: #ececee;
      }

      .el-input__inner::placeholder {
        color: #aaaaac;
        font-size: 14px;
        font-weight: 500;
      }
    }
    .problem_input_textarea {
      // height: 298px;
      background: #ececee;
      border-radius: 7px;
      .el-textarea__inner {
        height: 142px !important;
        border: none !important;
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        color: #39404d;
        line-height: 16px;
        background: #ececee;
        padding: 16px;
      }
      .el-textarea__inner::placeholder {
        color: #aaaaac;
        font-size: 14px;
        font-weight: 500;
      }

      .textarea_maxlength {
        font-size: 12px;
        font-weight: 500;
        text-align: right;
        color: #aaaaac;
        line-height: 14px;
        padding-right: 16px;
      }
      .textarea_img {
        display: flex;
        padding: 16px 0 16px 16px;
        align-items: flex-end;
        justify-content: space-between;
        flex-wrap: wrap;
        .textarea_img_div {
          .textarea_image {
            width: 72px !important;
            height: 72px !important;
            border-radius: 5px;
          }
          .van-uploader__upload {
            width: 72px !important;
            height: 72px !important;
            margin: 0 !important;
            border-radius: 5px;
            background: #ffffff !important;
            border: 1px solid #dcdfe6;
          }
          .van-uploader__preview {
            width: 72px !important;
            height: 72px !important;
            margin: 0 !important;
            margin-right: 10px !important;
            border-radius: 5px;
          }
          .van-uploader__preview-image {
            width: 72px !important;
            height: 72px !important;
            border-radius: 5px;
          }
          .van-uploader__preview-delete {
            width: 20px !important;
            height: 20px !important;
            border-radius: 0 5px 0 20px !important;
            background: var(--text-color) !important;
          }
          .van-uploader__preview-delete-icon {
            font-size: 20px !important;
          }
          .el-loading-mask {
            background: none !important;
          }
          .el-loading-spinner .path {
            stroke: var(--text-color);
          }
        }
      }
    }
  }

  .backImg {
    position: absolute;
    top: 0;
    left: 0;
    width: 44px;
    height: 44px;
    margin-left: 14px;
    z-index: 99;
  }

  .scanIcon {
    padding-top: 122px;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    // opacity: 1;
    // background-color: rgba(0, 0, 0, 0.5);

    .input_sno {
      width: calc(100% - 110px);
      height: 44px;
      margin-left: 55px;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .qrcode-stream-wrapper {
    opacity: 1;
    background-color: rgba(0, 0, 0, 0.5);
    width: 100%;
    height: 100vh;
    position: relative;
  }

  .qr-scanner .box {
    width: var(--snoWidth) !important;
    height: var(--snoWidth) !important;
    background: url('assets/img/common/scan@2x.png') no-repeat center;
    background-size: cover;
    margin-left: 55px;
    background-color: transparent !important;
    overflow: hidden;
    z-index: 9999;
    position: absolute;
  }

  .qr-scanner .line {
    height: calc(100%);
    width: calc(100% - 30px);
    margin-left: 15px;
    border-bottom: 2px solid #1f75bc;
    transform: translateY(-95%);
    animation: radar-beam 2s infinite alternate;
    animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
    animation-delay: 1.4s;
  }

  @keyframes radar-beam {
    0% {
      transform: translateY(-95%);
    }

    100% {
      transform: translateY(-5%);
    }
  }
}
</style>
